package com.ruoyi.loan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.loan.constant.ExamineStatus;
import com.ruoyi.loan.dto.SelectLoadDto;
import com.ruoyi.loan.dto.SelectReturnLoanListDto;
import com.ruoyi.loan.entity.LoanRecord;
import com.ruoyi.loan.entity.ReturnLoanRecord;
import com.ruoyi.loan.entity.User;
import com.ruoyi.loan.mapper.LoanRecordMapper;
import com.ruoyi.loan.mapper.ReturnLoanRecordMapper;
import com.ruoyi.loan.service.LoanRecordService;
import com.ruoyi.loan.utils.FileUtils;
import com.ruoyi.loan.vo.SelectLoanVo;
import com.ruoyi.loan.vo.SelectReturnLoanListPage;
import com.ruoyi.loan.vo.SelectReturnLoanListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author lin
 * @Date 2022/4/5 0:19
 */
@Service
public class LoanRecordServiceImpl extends ServiceImpl<LoanRecordMapper, LoanRecord> implements LoanRecordService {

    @Resource
    private LoanRecordMapper loanRecordMapper;

    @Resource
    private UserServiceImpl userService;

    @Resource
    private ReturnLoanRecordMapper returnLoanRecordMapper;

    @Autowired
    private FileUtils fileUtils;

    /**
     * 获取贷款信息列表
     * @param dto 参数信息
     * @return 贷款信息
     */
    @Override
    public PageInfo selectLoanList(SelectLoadDto dto) {
        PageHelper.startPage(dto.getPage(),dto.getLimit());
        List<SelectLoanVo> voList = new ArrayList<>();
        List<SelectLoanVo> selectLoanVos = loanRecordMapper.selectLoanList(dto);
        for (SelectLoanVo loanVo : selectLoanVos){
            Date adminTime = loanVo.getAdminTime();
            Date now = new Date();
            int adminTimeYear = adminTime == null ? now.getYear() : adminTime.getYear();
            int year = now.getYear() - adminTimeYear;
            int adminTimeMonth = adminTime == null ? now.getMonth() : adminTime.getMonth();
            int month = now.getMonth() - adminTimeMonth;
            Integer loanYears = loanVo.getLoanYears();
            int overtime = year * 12 + month - loanYears * 12;
            String overtimeStr = overtime < 0 ? "未逾期" : String.format("已逾期%d个月", overtime);
            loanVo.setOverdue(overtimeStr);
            String visitVoicePath = loanVo.getVisitVoicePath();
            if (visitVoicePath != null){
                loanVo.setVisitVoicePath(fileUtils.getShowFilePath(visitVoicePath));
            }
            Integer status = loanVo.getStatus();
            if (!ExamineStatus.EXAMINE.getCode().equals(status)){
                voList.add(loanVo);
            }
        }
        PageInfo pageInfo = new PageInfo(selectLoanVos);
        pageInfo.setList(voList);
        return pageInfo;
    }

    @Override
    public SelectReturnLoanListPage selectReturnLoanList(SelectReturnLoanListDto dto) {
        SelectReturnLoanListDto selectUserListDto = new SelectReturnLoanListDto();
        BeanUtils.copyProperties(dto,selectUserListDto);
        selectUserListDto.setPageNum(1);
        selectUserListDto.setPageSize(Integer.MAX_VALUE);
        // 查出符合条件的用户id
        PageInfo<User> pageInfo = userService.selectUserList(selectUserListDto);
        Set<Integer> userIdSet = pageInfo.getList().stream().map(User::getId).collect(Collectors.toSet());
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        QueryWrapper<ReturnLoanRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper = queryWrapper.in("user_id",userIdSet);
        // 查出符合条件的还款记录
        if (dto.getMinAmount() != null){
            queryWrapper = queryWrapper.ge("return_amount",dto.getMinAmount());
        }
        if (dto.getMaxAmount() != null){
            queryWrapper = queryWrapper.le("return_amount",dto.getMaxAmount());
        }
        List<ReturnLoanRecord> returnLoanRecordList = returnLoanRecordMapper.selectList(queryWrapper);
        PageInfo<ReturnLoanRecord> returnLoanRecordPageInfo = new PageInfo<>(returnLoanRecordList);
        List<SelectReturnLoanListVo> selectReturnLoanListVoList = new ArrayList<>();
        // 拼装用户信息和贷款信息
        for (ReturnLoanRecord returnLoanRecord : returnLoanRecordList) {
            Integer userId = returnLoanRecord.getUserId();
            Integer loanId = returnLoanRecord.getLoanId();
            User user = userService.selectUserById(userId);
            LoanRecord loanRecord = loanRecordMapper.selectById(loanId);
            SelectReturnLoanListVo selectReturnLoanListVo = new SelectReturnLoanListVo(user,loanRecord);
            BeanUtils.copyProperties(returnLoanRecord,selectReturnLoanListVo);
            selectReturnLoanListVoList.add(selectReturnLoanListVo);
        }
        SelectReturnLoanListPage page = new SelectReturnLoanListPage(selectReturnLoanListVoList, returnLoanRecordPageInfo.getTotal()
                , returnLoanRecordPageInfo.getPageNum(), returnLoanRecordPageInfo.getPageSize());
        return page;
    }

    @Override
    public PageInfo getVerityLoanList(SelectLoadDto dto) {
        PageHelper.startPage(dto.getPage(),dto.getLimit());
        List<SelectLoanVo> selectLoanVos = loanRecordMapper.getVerityLoanList(dto);
        PageInfo pageInfo = new PageInfo(selectLoanVos);
        return pageInfo;
    }
}
